package com.seed.bpmn.provider.activiti.service;

import com.seed.bpmn.engine.IBPMNHistoryService;
import com.seed.bpmn.engine.common.util.Empty;
import com.seed.bpmn.engine.dto.ProcessInstanceDTO;
import com.seed.bpmn.engine.dto.TaskDTO;
import com.seed.bpmn.provider.activiti.common.util.DTOUtil;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("bpmnHistoryService")
public class BPMNHistoryServiceImpl implements IBPMNHistoryService {

    @Autowired
    private HistoryService historyService;

    @Override
    public ProcessInstanceDTO getProcessInstance(String processInstanceId) throws Exception {
        HistoricProcessInstance p = this.historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        return DTOUtil.getProcessInstanceDTO(p);
    }

    @Override
    public ProcessInstanceDTO getProcessInstanceByBusinessKey(String businessKey) throws Exception {
        List<HistoricProcessInstance> list = this.historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).list();
        if(Empty.isNotEmpty(list)){
            return DTOUtil.getProcessInstanceDTO(list.get(0));
        }else{
            return null;
        }
    }

    @Override
    public ProcessInstanceDTO getFinishProcessInstance(String processInstanceId) {
        HistoricProcessInstance p = this.historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).finished().singleResult();
        return DTOUtil.getProcessInstanceDTO(p);
    }

    @Override
    public TaskDTO getTask(String taskId) throws Exception {
        HistoricTaskInstance t = this.historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        return DTOUtil.getTaskDTO(t);
    }

    @Override
    public List<TaskDTO> findTaskByProcessInstanceId(String processInstanceId) throws Exception {
        List<HistoricTaskInstance> tlist = this.historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list();

        List<TaskDTO> list = new ArrayList<TaskDTO>();
        for(HistoricTaskInstance t : tlist){
            if(Empty.isNotEmpty(t)){
                list.add(DTOUtil.getTaskDTO(t));
            }
        }

        return list;
    }
}
